package utils

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"net"
	"strings"
)

// GetClientIP 通过iris的context内部函数获取请求头部获取ip
func GetClientIP(ctx iris.Context) (string, error) {
	//从请求头部的X-REAL-IP获取Ip
	ip := ctx.Request().Header.Get("X-REAL-IP")
	netIP := net.ParseIP(ip)
	if netIP != nil {
		return ip, nil
	}

	//从请求头部的X-FORWARDED-FOR获取Ip
	ips := ctx.Request().Header.Get("X-FORWARDED-FOR")
	splitIps := strings.Split(ips, ",")
	for _, ip := range splitIps {
		netIP := net.ParseIP(ip)
		if netIP != nil {
			return ip, nil
		}
	}

	//从请求头部的RemoteAddr获取Ip
	ip, _, err := net.SplitHostPort(ctx.Request().RemoteAddr)
	if err != nil {
		return "", err
	}
	netIP = net.ParseIP(ip)
	if netIP != nil {
		return ip, nil
	}
	return "", fmt.Errorf("正确ip获取失败")
}
